<template>
  <div class="container">
    <el-form
      ref="articlesForm"
      :model="articleForm"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="文章标题" prop="title">
        <el-input
          placeholder="请输入文章标题"
          v-model="articleForm.title"
        ></el-input>
      </el-form-item>

      <!-- 文章内容 -->
      <el-form-item label="文章内容" prop="articleBody">
        <!-- 副文本编辑器 -->
        <div class="edit_container">
          <quill-editor
            v-model="articleForm.articleBody"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          >
          </quill-editor>
          <!-- 从数据库读取展示 -->
          <div v-html="str" class="ql-editor">
            {{ str }}
          </div>
        </div>
      </el-form-item>
      <!-- 视频地址 -->
      <el-form-item label="视频地址">
        <el-input v-model="articleForm.videoURL"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="cancelFn">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  add as addAPI,
  detail as detailAPI,
  update as updateAPI
} from '@/api/hmmm/articles.js'
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'articlesAdd',
  components: {
    quillEditor
  },
  props: {
    //   修改状态
    isEdit: {
      type: Boolean,
      required: true
    },
    // 当前文章的id
    currentId: {
      type: Number,
      default: null
    }
  },
  data () {
    // 校验文章标题
    const checkTitle = (rule, value, callback) => {
      if (!value) {
        callback(new Error('标题不能为空'))
      }
      callback()
    }
    // 校验文章内容
    const checkContent = (rule, value, callback) => {
      if (!value) {
        callback(new Error('文章内容不能为空'))
      }
      callback()
    }
    return {
      // 表单数据
      articleForm: {
        title: '', // 文章标题
        articleBody: '', // 文章的内容
        videoURL: '' // 视频地址
      },

      // 校验规则
      rules: {
        title: [
          { validator: checkTitle, trigger: 'blur' },
          { required: true, message: '请填写文章标题', trigger: 'blur' }
        ],
        articleBody: [
          { validator: checkContent, trigger: 'blur' },
          { required: true, message: '请填写文章内容', trigger: 'blur' }
        ]
      },

      editorOption: {
        // 副文本编辑器配置菜单
        placeholder: '请输入文章内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 上传图片、链接
          ]
        }
      },

      str: ''
    }
  },
  created () {
    //   获取文章详情数据并回填
    this.reviseArticleFn()
  },
  methods: {
    // 点击取消事件
    cancelFn () {
      this.$emit('close')
    },

    //   点击确定添加/修改
    onSubmit () {
      this.$refs.articlesForm.validate(async (valid) => {
        if (!valid) return false

        // 如果通过兜底验证,判断是不是修改状态
        this.isEdit ? this.updateArticleFn() : this.addArticleFn()

        this.$emit('close')
      })
    },

    // 添加文章
    async addArticleFn () {
      // 调用添加文章接口
      const res = await addAPI(this.articleForm)

      if (res.status === 200) {
        this.$message.success('新增文章成功')
      }
    },

    // 修改文章数据
    async updateArticleFn () {
      // 调用更新文章接口
      this.articleForm.id = this.currentId
      const res = await updateAPI(this.articleForm)
      if (res.data.success) {
        this.$message.success('修改文章成功')
      }
    },

    // 获取数据详情并回填
    async reviseArticleFn () {
      // 如果修改状态打开
      if (this.isEdit) {
        const res = await detailAPI({ id: this.currentId })

        // 数据回填
        this.articleForm = res.data
      }
    },

    // 准备编辑器
    onEditorReady (editor) {},

    onEditorBlur () {}, // 失去焦点事件

    onEditorFocus () {}, // 获得焦点事件

    onEditorChange () {}, // 内容改变事件

    // 把实体格式字符串转义成HTML格式的字符串
    escapeStringHTML (str) {
      str = str.replace(/&lt;/g, '<')
      str = str.replace(/&gt;/g, '>')
      return str
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
  mounted () {
    const content = '' // 请求后台返回的内容字符串
    this.str = this.escapeStringHTML(content)
  }
}
</script>

<style scoped >
.quill-editor {
  height: 200px;
  margin-bottom: 30px;
}
</style>
